class Friendship < ActiveRecord::Base
	belongs_to :entity
	belongs_to :friend, :class_name => 'Entity', :foreign_key => 'friend_id'
	
	has_one :friendship_request, :dependent => :destroy
	
	validates :entity_id, :presence => true
	validates :friend_id, :presence => true	
	validates_uniqueness_of  :friend_id, :scope => :entity_id
	
	before_create :ensure_unique_backward_relationship
	after_create :create_request_if_not_accepted
  after_create :ensure_puddles_created
	
	# Creates friend request on creation of Friendship row
	def create_request_if_not_accepted	
		if !self.accepted
			FriendshipRequest.create(:friendship_id => self.id)
		end	
	end	
	
	def ensure_unique_backward_relationship #Created by Adrian
		Friendship.find_by_entity_id_and_friend_id(self.friend_id,self.entity_id).nil?		
  end

  def ensure_puddles_created # Created by Adrian
    if self.accepted
      add_to_all_friends_puddle do |id_first,id_second|
        Entity.find(id_first).puddles.find_by_name("All Friends").add_entity(id_second)
      end
    end
  end
	#----------------------------------FRIENDSHIP REQUEST METHODS -----------------------------------------
	
	def accept_request #accept = destroy request - GRACE
		destroy_request
			
		self.update_attributes( :accepted => true)
    ensure_puddles_created #Edited by Adrian
	end
	
	def deny_request #deny = destroy request & friendship - GRACE
		self.destroy
	end
	
	def block_request # block friend request option, set accepted to nil - GRACE
		self.update_attributes( :accepted => nil)
		destroy_request
	end
	
	def destroy_request
		if !friendship_request.nil?
			friendship_request.destroy
		end
  end

  def add_to_all_friends_puddle #Created by Adrian
    yield(self.entity_id,self.friend_id) unless Group.exists?self.friend_id
    yield(self.friend_id,self.entity_id) unless Group.exists?self.entity_id
  end
end
